import Vue from 'vue'
// 一级路由

import VueRouter from 'vue-router'
// 二级路由

import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'

const Login = () => import('@/views/login')
const Myorder = () => import('@/views/myorder')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/pay', component: Pay },
    { path: '/prodetail/:id', component: ProDetail }
  ]
})

// 所有的路由在真正被访问之前，都会先经过全局前置守卫
// 只有前置守卫放行了，才会到达对应的组件
// 配置全局前置导航守卫
// to：到哪儿去，到哪儿去的完整路由信息对象（路径，参数）
// from：从哪里来，从哪儿来的完整路由信息对象（路径，参数）
// next（）：是否放行
// （1）next（） 直接放行，放行到to要去的路径
// （2）next（路径） 进行拦截，拦截到next里面配置的路径

// 定义一个数组，专门用户存放所有的需要权限访问的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
